<?php

namespace ApiBundle\Controller;

use AdminBundle\Entity\BaseDevice;
use AdminBundle\Entity\BaseDeviceExtra;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder;

class InitialController extends BaseController
{
    /**
     * client Initial generate token.
     *
     * @Route(path="/init", name="api_initial")
     * @Method({"GET", "POST"})
     */
    public function indexAction(Request $request)
    {
        // 返回结果参数
        $result = [];

        // 获取JSON包
        $data_template = [
            'user' => ['name' => '', 'password' => ''],
            'device' => ['name' => '', 'imei' => '', 'model' => '', 'os' => '', 'os_version' => '', 'mac' => '',
                'extra' => ['inner_ip' => '', 'bssid' => '', 'free_disk' => 0]]
        ];
        $data = $this->apiRequest($request, $data_template);

        // 身份验证
        if (($result['token'] = $this->authentication($data['user'])) == null) {
            return $this->apiJson(Response::HTTP_UNAUTHORIZED, '用户身份验证失败');
        }

        // 校验新增设备信息
        if (!$this->deviceNew($data['device'])) {
            return $this->apiJson(Response::HTTP_NOT_ACCEPTABLE, '参数不被接受');
        }

        //获取全局参数配置
        $result = array_merge($result, $this->globalParam());
        // 成功返回
        return $this->apiJson(0, '', $result);
    }

    /**
     * 身份验证,成功返回token
     * @param $user
     * @return null|string
     */
    private function authentication(&$user)
    {
        if (empty($user['name'])) {
            return null;
        }
        $em = $this->getDoctrine()->getManager();
        $authUser = $em->getRepository('AdminBundle:AuthUser')->findOneBy(['username' => $user['name']]);
        if ($authUser == null) {
            // 用户不存在
            return null;
        }
        $bcrypt = new BCryptPasswordEncoder($this->getParameter('bcrypt_cost'));
        if (!$bcrypt->isPasswordValid($authUser->getPassword(), $user['password'], '')) {
            // 密码不正确
            return null;
        }
        unset($bcrypt);

        return $authUser->getEmail();
    }

    /**
     * 获取全局参数配置
     * @return array
     */
    private function globalParam()
    {
        $result = [];
        //获取全局参数配置
        $em = $this->getDoctrine()->getManager();
        $baseGlobalParams = $em->getRepository('AdminBundle:BaseGlobalParam')->findBy(['isEnabled' => 1]);
        if ($baseGlobalParams != null) {
            foreach ($baseGlobalParams as $baseGlobalParam) {
                if (strpos($baseGlobalParam->getContent(), ',') > 0)
                    $result[$baseGlobalParam->getName()] = explode(',', $baseGlobalParam->getContent());
                else
                    $result[$baseGlobalParam->getName()] = $baseGlobalParam->getContent();
            }
        }
        return $result;
    }

    /**
     * 校验新增设备信息
     * @param $device
     * @return bool
     */
    private function deviceNew(&$device)
    {
        $result = false;
        if (empty($device['imei'])) {
            return $result;
        }
        $em = $this->getDoctrine()->getManager();

        $baseDevice = $em->getRepository('AdminBundle:BaseDevice')->findOneBy(['imei' => $device['imei']]);
        if ($baseDevice == null) {
            $result = true;
            $baseDevice = new BaseDevice();
            $baseDevice->setCtime(new \DateTime())
                ->setIp($this->ip)
                ->setCreator($this->username)
                ->setImei($device['imei']);
        }

        $baseDevice->setMacId($device['mac'])
            ->setModel($device['model'])
            ->setModel($device['model'])
            ->setOs($device['os'])
//            ->setOsVersion($device['os_version'])
            ->setGroupId(0)
            ->setGroupName('')
            ->setManufacturer('');

        $em->persist($baseDevice);
        $em->flush();

        $baseDeviceExtra = $em->getRepository('AdminBundle:BaseDeviceExtra')->findOneBy(['id' => $baseDevice->getId()]);
        if ($baseDeviceExtra == null) {
            $baseDeviceExtra = new BaseDeviceExtra();
        }

        $device_extra = $device['extra'];
        $baseDeviceExtra->setId($baseDevice->getId())
            ->setLastReportTime(new \DateTime())
            ->setLastRequestTime(new \DateTime())
            ->setLastRequestIp($this->ip)
            ->setOuterIp($this->ip)
            ->setInnerIp($device_extra['inner_ip'])
            ->setBssid($device_extra['bssid'])
            ->setFreeDisk($device_extra['free_disk']);

        $em->persist($baseDeviceExtra);
        $em->flush();

        return $result;
    }
}
